package com.fightingFish.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Created by Administrator on 2018/11/23.
 * 连接数据库工具类
 */
public class JdbcUtil {
    //定义用户名
    private final static String USERNAME;
    //定义密码
    private final static String PASSWORD;
    //定义URL地址
    private final static String URL;
    //定义加载驱动
    private final static String DRIVER;

    //加载驱动
    static {
        //读取JdbcConfig.properties文件
        Properties pro = new Properties();
        try {
            pro.load(JdbcUtil.class.getClassLoader().getResourceAsStream("com/fightingFish/util/JdbcConfig.properties"));
        } catch (IOException e) {
            e.printStackTrace();
            //手动抛出异常
            throw new RuntimeException(e.getMessage());
        }
        USERNAME = pro.getProperty("mysql.username");
        PASSWORD = pro.getProperty("mysql.password");
        URL = pro.getProperty("mysql.url");
        DRIVER = pro.getProperty("mysql.driver");
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //定义一个方法获取连接
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(URL,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭连接
    public static void close(Connection c, Statement s, ResultSet r){
        if (r != null){
            try {
                r.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (s != null){
            try {
                s.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (c != null){
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
